<?php
namespace app\admin\controller;

use think\Request;
use app\admin\controller\Admin;
use app\common\model\Book as BookModel;
use app\common\model\Section as SectionModel;
use app\common\model\Chapter as ChapterModel;

class Chapter extends Admin
{
    public function index()
    {
        $book_id = Request::instance()->param('id');
        $data['list'] = ChapterModel::getList(['c.book_id' => $book_id], 'id desc', 10);
        $data['book'] = BookModel::getInfo($book_id);
        $data['page'] = $data['list']->render();

        $this->assign('data', $data);

        return $this->fetch('admin/chapter/index');
    }

    public function create()
    {
        $book_id = Request::instance()->param('id');
        $data['section'] = SectionModel::getAll(['book_id' => $book_id], 'id desc');
        $data['book'] = BookModel::getInfo($book_id);
        $this->assign('data', $data);
        return $this->fetch('admin/chapter/create');
    }

    public function store()
    {
        $data = Request::instance()->param();
        $result =  ChapterModel::add($data);
        if (is_numeric($result )) {
            return $this->response(200);
        } else {
            return $this->response(201,$result );
        }

    }

    public function edit()
    {
        $id = Request::instance()->param('id');
        $data['chapter'] = ChapterModel::getInfo($id);
        $data['section'] = SectionModel::getAll(['book_id' => $data['chapter']['book_id']], 'id desc');
        $data['book'] = BookModel::getInfo($data['chapter']['book_id']);
        $this->assign('data', $data );

        return $this->fetch('admin/chapter/edit');
    }

    public function update()
    {
        $data = Request::instance()->param();
        $ret = ChapterModel::modify($data);

        if (is_numeric($ret)) {
            return $this->response(200);
        } else {
            return $this->response(201,$ret);
        }
    }

    public function remove()
    {
        $id = Request::instance()->param('id');
        $result = ChapterModel::remove($id);
        if ($result !== false) {
            return $this->response(200);
        } else {
            return $this->response(100);
        }
    }

}
